package com.xiaobias.distributed.pan.utils;

import java.text.DecimalFormat;

public class DataSizeUtil {

    // 单位大小
    public static final int UNIT_SIZE = 1024;

    // 显示单位
    public static final String[] UNIT_NAMES = new String[]{
            "B", "KB", "MB", "GB", "TB", "PB", "EB"
    };

    /**
     * 可读的文件大小
     *
     * @param size long
     * @return
     */
    public static String format(long size) {
        if (size <= 0) {
            return "0";
        }

        int digitGroups = Math.min(UNIT_NAMES.length - 1, (int) (Math.log10(size) / Math.log10(UNIT_SIZE)));
        String value = new DecimalFormat("#.#").format(size / Math.pow(UNIT_SIZE, digitGroups));
        return String.format("%s %s", value, UNIT_NAMES[digitGroups]);
    }
}